using System;
using NHibernate;

namespace CxRomos.Core.Domain {
    public class RepositoryBase {
        public ISession NHibernateSession {
            get { return NHibernateSessionManager.Instance.GetSession(); }
        }

        public CxRomosContext Context {
            get { return new CxRomosContext(NHibernateSession); }
        }

        public void BeginTransaction() {
            if (!NHibernateSessionManager.Instance.HasOpenTransaction())
                NHibernateSessionManager.Instance.BeginTransaction();
        }

        public void CommitChanges() {
            if (NHibernateSessionManager.Instance.HasOpenTransaction()) {
                try {
                    NHibernateSessionManager.Instance.GetSession().Flush();
                    NHibernateSessionManager.Instance.CommitTransaction();
                } catch (Exception ex) {
                    NHibernateSessionManager.Instance.RollbackTransaction();
                    NHibernateSessionManager.Instance.GetSession().Clear();
                    NHibernateSessionManager.Instance.CloseSession();
                    throw new Exception(ex.Message, ex);
                }
            } else
                NHibernateSessionManager.Instance.GetSession().Flush();
        }

    }
}